#include <ev.h>
#include <amqpcpp.h>
#include <amqpcpp/libev.h>
#include <openssl/ssl.h>
#include <openssl/opensslv.h>
#include <gflags/gflags.h>
#include "../../common/logger.hpp"

DEFINE_bool(run_mode, false, "程序的运行模式,0-调试,1-发布");
DEFINE_string(log_file, "", "发布模式下,用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下,用于指定日志的输出等级");

int main(int argc,char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    hdp::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);
    // 1. 实例化底层网络通信框架的I/O事件监控句柄
    // struct ev_loop *loop = ev_default_loop();
    struct ev_loop *loop = EV_DEFAULT;
    // 2. 实例化libEvHandler句柄 --- 将AMQP框架与事件监控关联起来
    AMQP::LibEvHandler handler(loop);
    // 3. 实例化连接对象
    AMQP::Address address("amqp://root:123456@127.0.0.1:5672/");
    AMQP::TcpConnection connection(&handler, address);
    // 4. 实例化信道对象
    AMQP::TcpChannel channel(&connection);
    // 5. 声明交换机
    channel.declareExchange("test-exchange", AMQP::ExchangeType::direct)
        .onError([](const char *message)
                 {
            LOG_ERROR("声明交换机失败:{}",message);
            exit(0); })
        .onSuccess([]()
                   { LOG_INFO("test-exchange交换机创建成功"); });
    // 6. 声明队列
    channel.declareQueue("test-queue")
        .onError([](const char *message)
                 {
            LOG_ERROR("声明队列失败:{}",message);
            exit(0); })
        .onSuccess([]()
                   { LOG_INFO("test-queue队列创建成功"); });
    // 7.针对交换机和队列进行绑定
    channel.bindQueue("test-exchange", "test-queue", "test-queue-key")
        .onError([](const char *message)
                 {
            LOG_ERROR("test-exchange - test-queue 绑定失败：{}",message);
            exit(0); })
        .onSuccess([]()
                   { LOG_INFO("test-exchange - test-queue 绑定成功！"); });
    // 8.向交换机发布消息
    for (int i = 0; i < 10; i++)
    {
        std::string msg = "Hello World" + std::to_string(i);
        bool ret = channel.publish("test-exchange", "test-queue-key", msg);
        if (ret == false)
        {
            LOG_ERROR("publish 失败");
            exit(0);
        }
    }
    // 9.启动底层网络通信框架--开启I/O
    ev_run(loop, 0);
    return 0;
}